package com.xiaoxu.auth.service.impl;

import com.xiaoxu.auth.service.SysMenuService;
import com.xiaoxu.auth.service.SysUserService;

import com.xiaoxu.common.exception.XiaoXuException;
import com.xiaoxu.common.result.ResultCodeEnum;
import com.xiaoxu.model.system.SysUser;
import com.xiaoxu.security.custom.CustomUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if(null == sysUser) {
            throw new XiaoXuException(201,"用户名不存在！");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        //查询已经分配的菜单 也就是授权的数据
        List<String> userPermsList = sysMenuService.findPermsByUserId(sysUser.getId());
        //创建list 集合，封装到SimpleGrantedAuthority权限数据
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();


        // 将用户权限列表中的每个权限转换为授权对象，并添加到授权列表中
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return new CustomUser(sysUser, authorities);

    }
}
